package com.zhou.springbootz10.webfluxweb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@RestController
public class WebFluxController {
    private Logger log = LoggerFactory.getLogger(getClass()); // 日志

    @GetMapping("webflux")
    public Mono<Map<String,String>> webflux(){
        return Mono.just(Map.of("msg","webflux")).delayElement(Duration.ofSeconds(1));
    }

    @GetMapping("webclient_demo")
    public Mono<Map> httpget(){
        return WebClient.create("http://localhost:8002").get()
                .uri("/webflux")
                .retrieve()
                .bodyToMono(Map.class);
    }

    @GetMapping("/random_numbers")
    public Flux<ServerSentEvent<Integer>> randomNumbers() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
                .map(data -> ServerSentEvent.<Integer>builder()
                        .event("random")
                        .id(Long.toString(data.getT1()))
                        .data(data.getT2())
                        .build());
    }

}
